package org.pms.demo.webservice.exception;

import org.apache.log4j.Logger;
import org.pms.demo.webservice.base.BaseException;
import org.pms.demo.webservice.base.ExceptionCode;
import org.pms.demo.webservice.utils.ProjectUtils;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * Created by laijianpeng on 17/10/20.
 */
@Provider
public class WebExceptionMapperSupport implements ExceptionMapper<WebApplicationException> {
    private static final Logger LOGGER = Logger
            .getLogger(WebExceptionMapperSupport.class);

    private static final String CONTEXT_ATTRIBUTE = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;

    @Context
    private HttpServletRequest request;

    @Context
    private ServletContext servletContext;

    /**
     * 异常处理
     *
     * @param exception
     * @return 异常处理后的Response对象
     */
    public Response toResponse(WebApplicationException exception) {

        String message = ExceptionCode.INTERNAL_SERVER_ERROR;
        Status statusCode = Status.INTERNAL_SERVER_ERROR;
        WebApplicationContext context = (WebApplicationContext) servletContext
                .getAttribute(CONTEXT_ATTRIBUTE);
        // 处理unchecked exception






        return Response.ok(ProjectUtils.getErrorMsg(String.valueOf(exception.getResponse().getStatus())), MediaType.TEXT_PLAIN).status(statusCode)
                .build();
    }
}